package com.example.simin_manage.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.simin_manage.admim.dto.Response;
import com.example.simin_manage.entity.OrderRecord;
import com.example.simin_manage.entity.PerformancePeriod;
import com.example.simin_manage.entity.PerformanceRule;
import com.example.simin_manage.entity.SysUser;
import com.example.simin_manage.mapper.OrderMapper;
import com.example.simin_manage.mapper.PerformancePeriodMapper;
import com.example.simin_manage.mapper.PerformanceRuleMapper;
import com.example.simin_manage.mapper.SysUserMapper;
import com.example.simin_manage.service.OrderService;
import com.example.simin_manage.service.PerformanceRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: panpan
 * @time: 2025/9/20
 */
@RestController
@RequestMapping("/api/rules")
public class PerformanceRuleController {

    @Autowired
    private PerformanceRuleService ruleService;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private PerformancePeriodMapper performancePeriodMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private PerformanceRuleMapper performanceRuleMapper;
    @Autowired
    private OrderService orderService;

    // 保存某周期的规则（覆盖保存）
    @PostMapping("/{cycleId}")
    public Response saveRules(@PathVariable Long cycleId, @RequestBody List<PerformanceRule> rules) {
        ruleService.saveRules(cycleId, rules);
        return new Response(200, "保存成功", null);
    }

    // 查询某周期的规则
    @GetMapping("/{cycleId}")
    public Response getRules(@PathVariable Long cycleId) {
        return new Response(200, "查询成功", ruleService.getRules(cycleId));
    }

    // 计算薪资
    @GetMapping("/{cycleId}/salary")
    public Response calcSalary(@PathVariable Long cycleId, @RequestParam int orders) {
        BigDecimal salary = ruleService.calculateSalary(cycleId, orders);
        return new Response(200, "计算成功", salary);
    }

    @GetMapping("/period/salary")
    public Response calculateSalaryByPeriod(@RequestParam Long userId) {
        // 用户校验
        SysUser user = userMapper.selectById(userId);
        if (user == null) {
            return new Response(404, "用户不存在", null);
        }

        // 找到当前绩效周期
        LocalDate today = LocalDate.now();
        PerformancePeriod currentPeriod = performancePeriodMapper.selectOne(
                new LambdaQueryWrapper<PerformancePeriod>()
                        .le(PerformancePeriod::getStartDate, today)
                        .ge(PerformancePeriod::getEndDate, today)
        );
        if (currentPeriod == null) {
            return new Response(404, "当前没有绩效周期", null);
        }

        // 查询总单量
        Object sumObj = orderMapper.selectObjs(
                new QueryWrapper<OrderRecord>()
                        .select("SUM(order_count)")
                        .eq("user_id", userId)
                        .ge("record_date", currentPeriod.getStartDate())
                        .le("record_date", currentPeriod.getEndDate())
        ).stream().findFirst().orElse(null);

        int totalOrders = sumObj == null ? 0 : ((Number) sumObj).intValue();

        // 获取当前周期的阶梯规则
        List<PerformanceRule> rules = performanceRuleMapper.selectList(
                new LambdaQueryWrapper<PerformanceRule>()
                        .eq(PerformanceRule::getCycleId, currentPeriod.getId())
                        .orderByAsc(PerformanceRule::getMinOrders)
        );

        // 计算薪资
        BigDecimal totalSalary = BigDecimal.ZERO;
        List<Map<String, Object>> breakdown = new ArrayList<>();

        if (totalOrders >= 100) {
            for (PerformanceRule r : rules) {
                int min = r.getMinOrders();
                int max = r.getMaxOrders() == null ? Integer.MAX_VALUE : r.getMaxOrders();
                BigDecimal price = BigDecimal.valueOf(r.getPricePerOrder());

                int applicable;
                if (min < 100) {
                    applicable = Math.min(totalOrders, max);
                } else {
                    if (totalOrders <= min) continue;
                    applicable = Math.min(totalOrders, max) - min;
                }

                if (applicable > 0) {
                    BigDecimal tierSalary = price.multiply(BigDecimal.valueOf(applicable));
                    totalSalary = totalSalary.add(tierSalary);

                    Map<String, Object> tierMap = new HashMap<>();
                    tierMap.put("range", min + "-" + (max == Integer.MAX_VALUE ? "以上" : max) + "单");
                    tierMap.put("price", price);
                    tierMap.put("orders", applicable);
                    tierMap.put("amount", tierSalary);
                    breakdown.add(tierMap);

                    // 调试打印
//                    System.out.printf("[区间 %d-%s单] 单价 ¥%.2f, 计薪订单 %d 单, 金额 ¥%.2f%n",
//                            min,
//                            max == Integer.MAX_VALUE ? "以上" : max,
//                            price,
//                            applicable,
//                            tierSalary
//                    );
                }
            }
        } else {
            // 小于100单不计薪
            Map<String, Object> zeroMap = new HashMap<>();
            zeroMap.put("range", "0-100单");
            zeroMap.put("price", BigDecimal.ZERO);
            zeroMap.put("orders", totalOrders);
            zeroMap.put("amount", BigDecimal.ZERO);
            breakdown.add(zeroMap);

//            System.out.printf("总单数: %d 小于100单，不计薪%n", totalOrders);
        }

        Map<String, Object> data = new HashMap<>();
        data.put("periodId", currentPeriod.getId());
        data.put("periodName", currentPeriod.getName());
        data.put("totalOrders", totalOrders);
        data.put("totalSalary", totalSalary);
        data.put("breakdown", breakdown);

        return new Response(200, "计算成功", data);
    }

    @GetMapping("/list")
    public Response listOrders(@RequestParam Long userId,
                               @RequestParam String startDate,
                               @RequestParam String endDate) {
        return orderService.listOrders(userId, startDate, endDate);
    }
}
